// 工具函数
const utils = {
    formatTime(seconds) {
        const mins = Math.floor(seconds / 60);
        const secs = seconds % 60;
        return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
    },

    showNotification(title, options = {}) {
        if (Notification.permission === 'granted') {
            new Notification(title, options);
        } else if (Notification.permission !== 'denied') {
            Notification.requestPermission().then(permission => {
                if (permission === 'granted') {
                    new Notification(title, options);
                }
            });
        }
    }
};

// 主题管理
const ThemeManager = {
    init() {
        const themeToggle = document.getElementById('themeToggle');
        const savedTheme = localStorage.getItem('theme') || 'light';
        
        document.documentElement.setAttribute('data-theme', savedTheme);
        themeToggle.querySelector('i').classList.toggle('fa-sun', savedTheme === 'dark');
        themeToggle.querySelector('i').classList.toggle('fa-moon', savedTheme === 'light');

        themeToggle.addEventListener('click', () => {
            const currentTheme = document.documentElement.getAttribute('data-theme');
            const newTheme = currentTheme === 'light' ? 'dark' : 'light';
            
            document.documentElement.setAttribute('data-theme', newTheme);
            localStorage.setItem('theme', newTheme);
            
            const icon = themeToggle.querySelector('i');
            icon.classList.toggle('fa-sun');
            icon.classList.toggle('fa-moon');
        });
    }
};

// 视图管理
const ViewManager = {
    init() {
        const navButtons = document.querySelectorAll('.nav-btn');
        const views = document.querySelectorAll('.view');

        navButtons.forEach(btn => {
            btn.addEventListener('click', () => {
                const targetView = btn.dataset.view;
                
                navButtons.forEach(nav => nav.classList.remove('active'));
                views.forEach(view => view.classList.remove('active'));
                
                btn.classList.add('active');
                document.getElementById(`${targetView}View`).classList.add('active');
            });
        });
    }
};

// 番茄钟管理
const PomodoroManager = {
    settings: {
        workDuration: 25 * 60,
        breakDuration: 5 * 60,
        autoStartBreak: false,
        autoStartWork: false
    },
    currentTime: 25 * 60,
    isRunning: false,
    isWorkTime: true,
    timer: null,
    progress: 0,

    init() {
        this.loadSettings();
        this.initializeElements();
        this.bindEvents();
        this.updateDisplay();
        this.updateProgress();
    },

    initializeElements() {
        this.elements = {
            display: document.getElementById('timerDisplay'),
            label: document.getElementById('timerLabel'),
            startBtn: document.getElementById('startTimer'),
            resetBtn: document.getElementById('resetTimer'),
            skipBtn: document.getElementById('skipTimer'),
            progressRing: document.querySelector('.progress-ring-circle'),
            floatingTime: document.getElementById('floatingTime'),
            floatingPlayPause: document.getElementById('floatingPlayPause')
        };

        // 设置进度环的初始属性
        const circle = this.elements.progressRing;
        const radius = circle.r.baseVal.value;
        const circumference = radius * 2 * Math.PI;
        circle.style.strokeDasharray = `${circumference} ${circumference}`;
        circle.style.strokeDashoffset = circumference;
    },

    bindEvents() {
        this.elements.startBtn.addEventListener('click', () => this.toggleTimer());
        this.elements.resetBtn.addEventListener('click', () => this.reset());
        this.elements.skipBtn.addEventListener('click', () => this.skip());
        this.elements.floatingPlayPause.addEventListener('click', () => this.toggleTimer());
    },

    toggleTimer() {
        if (this.isRunning) {
            this.pause();
        } else {
            this.start();
        }
    },

    start() {
        if (!this.isRunning) {
            this.isRunning = true;
            this.updateControls(true);
            
            this.timer = setInterval(() => {
                this.currentTime--;
                this.updateDisplay();
                this.updateProgress();

                if (this.currentTime <= 0) {
                    this.completeInterval();
                }
            }, 1000);
        }
    },

    pause() {
        if (this.isRunning) {
            this.isRunning = false;
            clearInterval(this.timer);
            this.updateControls(false);
        }
    },

    reset() {
        this.pause();
        this.currentTime = this.isWorkTime ? this.settings.workDuration : this.settings.breakDuration;
        this.updateDisplay();
        this.updateProgress();
    },

    skip() {
        this.completeInterval();
    },

    completeInterval() {
        this.pause();
        
        if (this.isWorkTime) {
            // 完成一个工作时段
            this.isWorkTime = false;
            this.currentTime = this.settings.breakDuration;
            utils.showNotification('工作时间结束', {
                body: '该休息一下了！',
                icon: '/icon.png'
            });
            
            if (this.settings.autoStartBreak) {
                this.start();
            }
        } else {
            // 完成一个休息时段
            this.isWorkTime = true;
            this.currentTime = this.settings.workDuration;
            utils.showNotification('休息时间结束', {
                body: '准备开始新的工作时段！',
                icon: '/icon.png'
            });
            
            if (this.settings.autoStartWork) {
                this.start();
            }
        }
        
        this.updateDisplay();
        this.updateProgress();
    },

    updateDisplay() {
        const timeString = utils.formatTime(this.currentTime);
        this.elements.display.textContent = timeString;
        this.elements.floatingTime.textContent = timeString;
        this.elements.label.textContent = this.isWorkTime ? '工作时间' : '休息时间';
    },

    updateProgress() {
        const circle = this.elements.progressRing;
        const radius = circle.r.baseVal.value;
        const circumference = radius * 2 * Math.PI;
        
        const totalTime = this.isWorkTime ? this.settings.workDuration : this.settings.breakDuration;
        const progress = this.currentTime / totalTime;
        const offset = circumference - (progress * circumference);
        
        circle.style.strokeDashoffset = offset;
    },

    updateControls(isRunning) {
        const startIcon = this.elements.startBtn.querySelector('i');
        const floatingIcon = this.elements.floatingPlayPause.querySelector('i');
        
        startIcon.classList.toggle('fa-play', !isRunning);
        startIcon.classList.toggle('fa-pause', isRunning);
        floatingIcon.classList.toggle('fa-play', !isRunning);
        floatingIcon.classList.toggle('fa-pause', isRunning);
    },

    loadSettings() {
        const savedSettings = localStorage.getItem('pomodoroSettings');
        if (savedSettings) {
            this.settings = { ...this.settings, ...JSON.parse(savedSettings) };
        }
    },

    saveSettings() {
        localStorage.setItem('pomodoroSettings', JSON.stringify(this.settings));
    }
};

// 任务管理
const TaskManager = {
    tasks: [],
    currentFilter: 'all',

    init() {
        this.loadTasks();
        this.initializeElements();
        this.bindEvents();
        this.renderTasks();
    },

    initializeElements() {
        this.elements = {
            tasksList: document.getElementById('tasksGrid'),
            addTaskBtn: document.getElementById('addTaskBtn'),
            taskModal: document.getElementById('taskModal'),
            taskForm: document.getElementById('taskForm'),
            saveTaskBtn: document.getElementById('saveTaskBtn'),
            quickAddInput: document.getElementById('quickAddTask'),
            quickAddBtn: document.getElementById('quickAddBtn')
        };
    },

    bindEvents() {
        this.elements.addTaskBtn.addEventListener('click', () => {
            this.elements.taskModal.classList.add('active');
        });

        this.elements.saveTaskBtn.addEventListener('click', () => this.saveTask());

        document.querySelectorAll('.close-btn').forEach(btn => {
            btn.addEventListener('click', () => {
                this.elements.taskModal.classList.remove('active');
            });
        });

        document.querySelectorAll('.filter-btn').forEach(btn => {
            btn.addEventListener('click', () => {
                this.currentFilter = btn.dataset.filter;
                this.renderTasks();
            });
        });

        this.elements.quickAddBtn.addEventListener('click', () => this.quickAddTask());
        this.elements.quickAddInput.addEventListener('keypress', (e) => {
            if (e.key === 'Enter') {
                this.quickAddTask();
            }
        });
    },

    quickAddTask() {
        const input = this.elements.quickAddInput;
        const title = input.value.trim();
        
        if (title) {
            const task = {
                id: Date.now(),
                title,
                pomodoros: 1,
                completed: false,
                createdAt: new Date().toISOString(),
                priority: 'medium'
            };

            this.tasks.unshift(task);
            this.saveTasks();
            this.renderTasks();
            input.value = '';
        }
    },

    saveTask() {
        const formData = new FormData(this.elements.taskForm);
        const task = {
            id: Date.now(),
            title: formData.get('taskTitle'),
            pomodoros: parseInt(formData.get('taskPomodoros')),
            priority: formData.get('taskPriority'),
            date: formData.get('taskDate'),
            tags: formData.get('taskTags').split(',').map(tag => tag.trim()).filter(Boolean),
            notes: formData.get('taskNotes'),
            completed: false,
            createdAt: new Date().toISOString()
        };

        this.tasks.unshift(task);
        this.saveTasks();
        this.renderTasks();
        this.elements.taskModal.classList.remove('active');
        this.elements.taskForm.reset();
    },

    toggleTask(id) {
        const task = this.tasks.find(t => t.id === id);
        if (task) {
            task.completed = !task.completed;
            this.saveTasks();
            this.renderTasks();
        }
    },

    deleteTask(id) {
        this.tasks = this.tasks.filter(t => t.id !== id);
        this.saveTasks();
        this.renderTasks();
    },

    renderTasks() {
        const filteredTasks = this.filterTasks();
        this.elements.tasksList.innerHTML = '';

        filteredTasks.forEach(task => {
            const taskElement = document.createElement('div');
            taskElement.className = `task-card priority-${task.priority}`;
            taskElement.innerHTML = `
                <div class="task-header">
                    <label class="checkbox">
                        <input type="checkbox" ${task.completed ? 'checked' : ''}>
                        <span class="checkmark"></span>
                    </label>
                    <h3>${task.title}</h3>
                    <button class="delete-btn">
                        <i class="fas fa-trash"></i>
                    </button>
                </div>
                <div class="task-meta">
                    <span><i class="fas fa-clock"></i> ${task.pomodoros} 个番茄钟</span>
                    ${task.date ? `<span><i class="fas fa-calendar"></i> ${task.date}</span>` : ''}
                </div>
                ${task.tags && task.tags.length ? `
                    <div class="task-tags">
                        ${task.tags.map(tag => `<span class="tag">${tag}</span>`).join('')}
                    </div>
                ` : ''}
            `;

            const checkbox = taskElement.querySelector('input[type="checkbox"]');
            checkbox.addEventListener('change', () => this.toggleTask(task.id));

            const deleteBtn = taskElement.querySelector('.delete-btn');
            deleteBtn.addEventListener('click', () => this.deleteTask(task.id));

            this.elements.tasksList.appendChild(taskElement);
        });
    },

    filterTasks() {
        return this.tasks.filter(task => {
            switch (this.currentFilter) {
                case 'today':
                    return task.date === new Date().toISOString().split('T')[0];
                case 'upcoming':
                    return !task.completed && task.date;
                case 'completed':
                    return task.completed;
                default:
                    return true;
            }
        });
    },

    loadTasks() {
        const savedTasks = localStorage.getItem('tasks');
        if (savedTasks) {
            this.tasks = JSON.parse(savedTasks);
        }
    },

    saveTasks() {
        localStorage.setItem('tasks', JSON.stringify(this.tasks));
    }
};

// 白噪音管理
const SoundManager = {
    sounds: {},
    activeSounds: 0,

    init() {
        this.initializeSounds();
        this.bindEvents();
    },

    initializeSounds() {
        const soundItems = document.querySelectorAll('.sound-item');
        
        soundItems.forEach(item => {
            const soundId = item.dataset.sound;
            const audio = new Audio(`sounds/${soundId}.mp3`);
            audio.loop = true;

            this.sounds[soundId] = {
                audio,
                isPlaying: false,
                volume: 0.5
            };

            const button = item.querySelector('.sound-btn');
            const slider = item.querySelector('.volume-slider');

            button.addEventListener('click', () => this.toggleSound(soundId));
            slider.addEventListener('input', (e) => this.updateVolume(soundId, e.target.value / 100));
        });
    },

    toggleSound(soundId) {
        const sound = this.sounds[soundId];
        const soundItem = document.querySelector(`[data-sound="${soundId}"]`);
        
        if (sound.isPlaying) {
            sound.audio.pause();
            sound.isPlaying = false;
            this.activeSounds--;
            soundItem.classList.remove('playing');
        } else {
            sound.audio.play();
            sound.isPlaying = true;
            this.activeSounds++;
            soundItem.classList.add('playing');
        }

        this.updateActiveSoundsCount();
    },

    updateVolume(soundId, value) {
        const sound = this.sounds[soundId];
        sound.volume = value;
        sound.audio.volume = value;
    },

    updateActiveSoundsCount() {
        document.getElementById('activeSoundsCount').textContent = this.activeSounds;
    }
};

// 统计管理
const StatsManager = {
    init() {
        this.initializeChart();
        this.bindEvents();
    },

    initializeChart() {
        const ctx = document.getElementById('focusChart').getContext('2d');
        this.chart = new Chart(ctx, {
            type: 'line',
            data: {
                labels: [],
                datasets: [{
                    label: '专注时长（分钟）',
                    data: [],
                    borderColor: '#6366f1',
                    tension: 0.4
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        display: false
                    }
                },
                scales: {
                    y: {
                        beginAtZero: true
                    }
                }
            }
        });
    },

    bindEvents() {
        document.querySelectorAll('.range-btn').forEach(btn => {
            btn.addEventListener('click', () => {
                document.querySelectorAll('.range-btn').forEach(b => b.classList.remove('active'));
                btn.classList.add('active');
                this.updateStats(btn.dataset.range);
            });
        });
    },

    updateStats(range) {
        // 这里添加统计数据更新逻辑
    }
};

// 设置管理
const SettingsManager = {
    init() {
        this.initializeElements();
        this.bindEvents();
        this.loadSettings();
    },

    initializeElements() {
        this.elements = {
            settingsBtn: document.getElementById('settingsBtn'),
            settingsModal: document.getElementById('settingsModal'),
            saveSettingsBtn: document.getElementById('saveSettingsBtn')
        };
    },

    bindEvents() {
        this.elements.settingsBtn.addEventListener('click', () => {
            this.elements.settingsModal.classList.add('active');
        });

        this.elements.saveSettingsBtn.addEventListener('click', () => this.saveSettings());

        document.querySelectorAll('.close-btn').forEach(btn => {
            btn.addEventListener('click', () => {
                this.elements.settingsModal.classList.remove('active');
            });
        });
    },

    loadSettings() {
        const savedSettings = localStorage.getItem('settings');
        if (savedSettings) {
            const settings = JSON.parse(savedSettings);
            Object.entries(settings).forEach(([key, value]) => {
                const element = document.getElementById(key);
                if (element) {
                    if (element.type === 'checkbox') {
                        element.checked = value;
                    } else {
                        element.value = value;
                    }
                }
            });
        }
    },

    saveSettings() {
        const settings = {
            workDuration: document.getElementById('workDuration').value,
            breakDuration: document.getElementById('breakDuration').value,
            soundNotification: document.getElementById('soundNotification').checked,
            desktopNotification: document.getElementById('desktopNotification').checked,
            autoStartBreak: document.getElementById('autoStartBreak').checked,
            autoStartWork: document.getElementById('autoStartWork').checked
        };

        localStorage.setItem('settings', JSON.stringify(settings));
        PomodoroManager.settings = {
            ...PomodoroManager.settings,
            workDuration: settings.workDuration * 60,
            breakDuration: settings.breakDuration * 60,
            autoStartBreak: settings.autoStartBreak,
            autoStartWork: settings.autoStartWork
        };
        
        this.elements.settingsModal.classList.remove('active');
    }
};

// 初始化应用
document.addEventListener('DOMContentLoaded', () => {
    ThemeManager.init();
    ViewManager.init();
    PomodoroManager.init();
    TaskManager.init();
    SoundManager.init();
    StatsManager.init();
    SettingsManager.init();
});
